package android.slc.utils;

import android.slc.rx.SimpleSingleObserver;
import android.slc.rx.SlcRxJavaUtils;
import cn.hutool.core.io.resource.NoResourceException;
import cn.hutool.core.io.resource.Resource;
import cn.hutool.core.io.resource.ResourceUtil;
import cn.hutool.core.util.URLUtil;
import io.reactivex.rxjava3.annotations.NonNull;
import io.reactivex.rxjava3.core.Single;
import io.reactivex.rxjava3.disposables.Disposable;

import java.util.concurrent.TimeUnit;

public class SlcSystemUtils {
    private static Disposable currentGcDisposable;

    public static void tryGc() {
        tryGc(0);
    }

    public static void tryGc(long delayed) {
        stopCurrentGc();
        if (delayed <= 0) {
            System.gc();
            return;
        }
        Single.timer(delayed, TimeUnit.MILLISECONDS).compose(SlcRxJavaUtils.applyOsAndroidSchedulers())
                .subscribe(new SimpleSingleObserver<Long>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {
                        super.onSubscribe(d);
                        SlcSystemUtils.currentGcDisposable = d;
                    }

                    @Override
                    public void onSuccess(@NonNull Long aLong) {
                        super.onSuccess(aLong);
                        System.gc();
                        SlcSystemUtils.currentGcDisposable = null;
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                        super.onError(e);
                        SlcSystemUtils.currentGcDisposable = null;
                    }
                });
    }

    private static void stopCurrentGc() {
        if (currentGcDisposable != null && !currentGcDisposable.isDisposed()) {
            currentGcDisposable.dispose();
            currentGcDisposable = null;
        }
    }

    /**
     * 是否运行在jar包中，而非开发工具中
     *
     * @return
     */
    public static boolean runJarMode() {
        return runJarMode("system/run-jar-perception");
    }

    /**
     * 是否运行在jar包中，而非开发工具中
     *
     * @param resPath
     * @return
     */
    public static boolean runJarMode(String resPath) {
        try {
            Resource resourceObj = ResourceUtil.getResourceObj(resPath);
            return URLUtil.isJarURL(resourceObj.getUrl());
        } catch (NoResourceException e) {
            return false;
        }
    }
}
